/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteSocket.java
 *
 * Created on 27/10/2010, 06:53:48 AM
 */

package cliente;

import com.thoughtworks.xstream.XStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


/**
 *
 * @author Francisco Gomez
 */
public class ClienteSocket extends javax.swing.JFrame {

    /** Creates new form ClienteSocket */
    Cliente cliente;
    Socket socketCliente;
    VentanaEstadoTarea ventanaEstadoTarea;
    int puerto;
    
    public ClienteSocket() {
        initComponents();
        cliente = new Cliente(this);
        for (Configuracion configuracion : cliente.getConfiguracion()) {
            ClienteManejadorArchivos.getInstance("", "").agregarServidor(configuracion.getIp());
            this.IpServidor.setText(ClienteManejadorArchivos.getInstance("", "").getServerIp(0));
            txtPort.setText(configuracion.getPuerto());
        }
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        textNombre = new javax.swing.JTextField();
        textPass = new javax.swing.JPasswordField();
        IpServidor = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("IP Server:");

        txtPort.setEditable(false);

        jLabel3.setText("Port Server:");

        jButton2.setText("Enviar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Nombre:");

        jLabel5.setText("Password:");

        textNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textNombreActionPerformed(evt);
            }
        });

        textPass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textPassActionPerformed(evt);
            }
        });

        IpServidor.setEditable(false);
        IpServidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                IpServidorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(IpServidor)
                    .addComponent(jButton2)
                    .addComponent(textNombre)
                    .addComponent(txtPort, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                    .addComponent(textPass))
                .addGap(77, 77, 77))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(IpServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(textPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addComponent(jButton2)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        comprobarRegistro();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void textNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textNombreActionPerformed

    private void textPassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPassActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textPassActionPerformed

private void IpServidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IpServidorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_IpServidorActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClienteSocket().setVisible(true);
            }
        });
    }

    private void comprobarRegistro(){
        String ip = this.IpServidor.getText();
        int port = Integer.valueOf(this.txtPort.getText());
        String usuario = textNombre.getText();
        String clave = textPass.getText();
        String respuesta;
        String comando;
        int intentos = 0;
        Boolean flag = true;
        while (flag == true){
        try {
            ip = this.IpServidor.getText();
            this.socketCliente = new Socket(ip, port);
            PrintWriter salida = new PrintWriter(this.socketCliente.getOutputStream(), true);
            BufferedReader entrada = new BufferedReader(new InputStreamReader(this.socketCliente.getInputStream()));
          //  salida.println(usuario + "." + clave);
            salida.println("<Usuario>"+usuario+"</Usuario>");
            salida.println("<Clave>"+clave+"</Clave>");
            
            respuesta = entrada.readLine();
            comando = entrada.readLine();


            if (XmlParser.extraerContenido(respuesta).equals("Ok")) {
                this.puerto = Integer.parseInt(XmlParser.extraerContenido(comando));
                JOptionPane.showMessageDialog(this, "Ya estas logeado", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                salida.close();
                entrada.close();
                this.socketCliente.close();
                this.setVisible(false);
                System.out.println(textNombre.getText() + " " + this.IpServidor.getText());
                ventanaEstadoTarea = new VentanaEstadoTarea(textNombre.getText(), textPass.getText(), puerto, this.IpServidor.getText());
                ventanaEstadoTarea.setVisible(true);
                flag = false;
            } else {
                flag = false;
                JOptionPane.showMessageDialog(this, "Nombre o password incorrecto", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            }

        } catch (Exception e) {
            intentos++;
            if (intentos <= 2){
                    this.IpServidor.setText(ClienteManejadorArchivos.getInstance("", "").getServerIp(intentos));
            }else{
            flag = false;    
            mensajeError(e);
        }
        }
        }
    }
    
    
    private void mensajeError(Exception exception){
        
        String exceptionString = exception.getClass().getName().toString();
        StringTokenizer tokens = new StringTokenizer(exceptionString,".");
        boolean errorConexion = false;

        try{
            while (tokens.hasMoreTokens()){
                String exceptionStringConnect = tokens.nextToken();
                System.out.println(exceptionStringConnect);
                if (exceptionStringConnect.equalsIgnoreCase("ConnectException")){
                    JOptionPane.showMessageDialog(rootPane, "No existe conexión con el servidor", "Error", JOptionPane.ERROR_MESSAGE);
                    errorConexion = true;
                    break;
                }                    
            }
        } catch (Exception e){
            
        }
        
        if (!errorConexion)
            JOptionPane.showMessageDialog(rootPane, "Error durante la ejecución del programa", "Error", JOptionPane.ERROR_MESSAGE);
    }
    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField IpServidor;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField textNombre;
    private javax.swing.JPasswordField textPass;
    private javax.swing.JTextField txtPort;
    // End of variables declaration//GEN-END:variables

}
